package user

import (
	"encoding/json"
	"fmt"
	"server/base"
	"server/common/models/user"
)

var redis_user_contact_find_by_user_id_expr = 60 * 60 * 12
var redis_user_contact_find_by_user_id = "user_contact_find_by_user_id_%d_%d"

type userContacts struct{}

func (userContacts) getRedisKey(userId int64, contactId int64) string {
	return fmt.Sprintf(redis_user_contact_find_by_user_id, userId, contactId)

}

func (u userContacts) GetContactByUserId(userId int64, ContactId int64) (user.UserContact, error) {
	var UserContacts user.UserContact
	res, err := base.App.Redis.Get(u.getRedisKey(userId, ContactId))
	if err != nil || res == "" {
		err = base.Mysql.Find(&UserContacts, "user_id = ? and contact_id = ?", userId, ContactId).Error
		if err != nil {
			return UserContacts, err
		}

		_, err = base.App.Redis.Set(u.getRedisKey(userId, ContactId), UserContacts.ToString(), int64(redis_user_contact_find_by_user_id_expr))
		return UserContacts, nil
	}
	err = json.Unmarshal([]byte(res), &UserContacts)
	return UserContacts, err
}
